<template>
  <div class="addGoods-container">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-alert
        title="添加商品信息"
        type="info"
        center
        show-icon
        close-text=" "
      >
      </el-alert>
      <el-steps :active="active - 0" align-center finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <el-form
        :model="addGoods"
        class="demo-ruleForm"
        label-position="top"
        :rules="rulesAddGoods"
        ref="addFormRef"
      >
        <el-tabs
          v-model="active"
          :tab-position="tabPosition"
          :before-leave="beforeTabLeave"
          @tab-click="tabClicked"
        >
          <!-- 基本信息 -->
          <el-tab-pane label="基本信息" name="0">
            <div>
              <el-form-item label="商品名称" prop="goods_name">
                <el-input v-model="addGoods.goods_name"></el-input>
              </el-form-item>
              <el-form-item label="商品价格" prop="goods_price">
                <el-input
                  v-model="addGoods.goods_price"
                  type="number"
                ></el-input>
              </el-form-item>
              <el-form-item label="商品重量" prop="goods_weight">
                <el-input
                  v-model="addGoods.goods_weight"
                  type="number"
                ></el-input>
              </el-form-item>
              <el-form-item label="商品数量" prop="goods_number">
                <el-input
                  v-model="addGoods.goods_number"
                  type="number"
                ></el-input>
              </el-form-item>
              <el-form-item label="商品分类" prop="goods_cat">
                <el-cascader
                  v-model="addGoods.goods_cat"
                  :options="cateList"
                  expand-trigger="hover"
                  :props="cateProps"
                  @change="handleChange"
                ></el-cascader>
              </el-form-item>
            </div>
          </el-tab-pane>
          <!-- 商品参数 -->
          <el-tab-pane label="商品参数" @click="changeActive" name="1">
            <el-form-item
              v-for="item in manyTableData"
              :key="item.attr_id"
              :label="item.attr_name"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  :label="cb"
                  v-for="(cb, i) in item.attr_vals"
                  :key="i"
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>

          <!-- 商品属性 -->
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="item.attr_name"
              prop="name"
              v-for="item in onlyTableDate"
              :key="item.attr_id"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品图片 -->
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              :action="uploadURl"
              :on-change="handleChangeImg"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headerObj"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <!-- 商品内容 -->
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器 -->
            <quill-editor v-model="addGoods.goods_introducce"> </quill-editor>
            <el-button type="primary" @click="add">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import {
  addGoods,
  getCateList,
  getGoodsParameter,
  getGoodsAttribute,
} from "@/api/goods";
import { mapGetters } from "vuex";
import _ from "lodash";
export default {
  name: "",
  components: {},
  props: {},
  data() {
    return {
      fileList: [],
      // 商品列表
      addGoods: {
        goods_name: "", // 商品名字
        goods_price: 0, // 价格
        goods_number: 0, //数量
        goods_weight: 0, // 重量
        goods_cat: [], //商品所属分类的数组
        goods_introducce: "", //商品详情
        attrs: [], //
        pics: [],
      },
      // 商品分类列表
      cateList: [],
      cateProps: {
        label: "cat_name",
        value: "cat_id",
        children: "children",
      },
      // 校验规则
      rulesAddGoods: {
        goods_name: [
          {
            required: true,
            message: "请输入商品名称",
            trigger: "blur",
          },
        ],
        goods_price: [
          {
            required: true,
            message: "请输入商品价格",
            trigger: "blur",
          },
        ],
        goods_weight: [
          {
            required: true,
            message: "请输入商品重量",
            trigger: "blur",
          },
        ],
        goods_number: [
          {
            required: true,
            message: "请输入商品数量",
            trigger: "blur",
          },
        ],
        goods_cat: [
          {
            required: true,
            message: "请选择商品分类",
            trigger: "blur",
          },
        ],
      },
      tabPosition: "left",
      // tab 栏 切换的索引
      active: 0,
      manyTableData: [], // 动态参数列表数据
      onlyTableDate: [], //静态参数数据列表
      uploadURl: "https://www.liulongbin.top:8888/api/private/v1/upload", //上传图片的地址
      headerObj: {
        Authorization: this.token,
      },
    };
  },
  computed: {
    ...mapGetters(["token"]),
    cateId() {
      if (this.addGoods.goods_cat.length === 3) {
        return this.addGoods.goods_cat[2];
      }
      return null;
    },
  },
  watch: {},
  created() {
    // 获取商品列表
    this.getCateList();
    // console.log(this.token);
  },
  methods: {
    // 处理图片预览效果
    handleChangeImg(file, fileList) {
      this.fileList = fileList.slice(-3);
    },
    changeActive() {
      this.active = 1;
    },
    // 删除图片的操作
    handleRemove() {},
    handleChange(value) {
      if (this.addGoods.goods_cat.length !== 3) {
        this.addGoods.goods_cat = [];
      }
    },
    // 获取商品数据列表
    async getCateList() {
      const { data } = await getCateList();
      // console.log(data);
      if (data.meta.status !== 200)
        return this.message.error("获取分类数据失败!");
      this.cateList = data.data;
    },
    beforeTabLeave(activeName, oldActiveName) {
      if (oldActiveName === "0" && this.addGoods.goods_cat.length !== 3) {
        this.$message.error("请先选择商品分类");
        return false;
      }
    },
    // tab 栏切换触发的函数
    async tabClicked() {
      if (this.active === "1") {
        // console.log(1);
        const { data } = await getGoodsParameter(this.cateId);
        // console.log(data);
        if (data.meta.status !== 200) {
          this.$message.error("获取失败");
        }
        data.data.forEach((item) => {
          item.attr_vals =
            item.attr_vals.length === 0 ? [] : item.attr_vals.split(" ");
        });
        this.manyTableData = data.data;
        console.log(this.manyTableData);
      } else if (this.active === "2") {
        const { data: res } = await getGoodsAttribute(this.cateId);
        if (res.meta.status !== 200) {
          this.$message.error("获取静态列表失败");
        }
        this.onlyTableDate = res.data;
      }
    },
    add() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) {
          this.$message.error("请填写必要表单项");
        }
        const form = _.cloneDeep(this.addGoods);
        console.log(form);
        form.goods_cat = form.goods_cat.join(",");
        // console.log(form);
        // 处理动态数据
        this.manyTableData.forEach((item) => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(" "),
          };
          this.addGoods.attrs.push(newInfo);
        });
        // 处理静态数据
        this.onlyTableDate.forEach((item) => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals,
          };
          this.addGoods.attrs.push(newInfo);
        });
        form.attrs = this.addGoods.attrs;
        const { data } = await addGoods(form);
        console.log(form);
        // console.log(data);
        console.log(data);
        if (data.meta.status !== 201)
          return this.$message.error(data.meta.msg || "添加失败!");
        this.$message.success("添加成功！");
        this.$router.push("/goods");
      });
    },
  },
};
</script>

<style scoped lang='sass'>
.addGoods-container
  padding: 20px
.el-alert--info
  margin-bottom: 15px

.el-steps--horizontal
  margin-bottom: 40px

.el-step__title
  font-size: 12px

.box-card
  margin-top: 20px
.el-checkbox
  margin: 0 10px 0 0 !important
.ql-snow
  height: 300px !important
</style>